<?php

$db = new Database();

$formID = $_POST['FormID'];
$insert_result = $_POST['ID'];
$node_id = $_POST['Node_ID'];

$myRequest = new Request();
$myRequest->load($formID, $insert_result);

$fields = array();
$fieldResults = $myRequest->fields;
$date = $this->currentDateTime();
$fieldEnabled = json_decode($_POST['fieldEnabled']);
$reservedFields = array("TrackNo", "Requestor", "Status", "Processor", "LastAction", "DateCreated", "DateUpdated", "CreatedBy", "UpdatedBy", "Unread", "Node_ID", "Workflow_ID"
    , "fieldEnabled", "fieldRequired", "fieldHiddenValues", "imported");


foreach ($fieldResults as $field) {

//    $index_search = in_array($field['COLUMN_NAME'], $fieldEnabled);
//    $reserved_index = in_array($field['COLUMN_NAME'], $reservedFields);
    // if ($index_search || $reserved_index){
    if (is_array($_POST[$field['COLUMN_NAME']])) {
        $fields[$field['COLUMN_NAME']] = join(",", $_POST[$field['COLUMN_NAME']]);
    } else if ($field['COLUMN_NAME'] == 'DateCreated' && $insert_result == '0') {
        $fields[$field['COLUMN_NAME']] = $date;
    } else if ($field['COLUMN_NAME'] == 'DateUpdated') {
        $fields[$field['COLUMN_NAME']] = $date;
    } else {
        if ($_POST[$field['COLUMN_NAME']] != "null" && $_POST[$field['COLUMN_NAME']] != null) {
            $fields[$field['COLUMN_NAME']] = $_POST[$field['COLUMN_NAME']];
        }
    }
    // }
}

if ($insert_result == '0') {
    $myRequest->data = $fields;
    $myRequest->save();
} else {
    if ($node_id == 'Cancel') {
        $fields['Status'] = 'Cancelled';
        $fields['Processor'] = '';
        $fields['LastAction'] = '';
    }

    if ($node_id == 'Save' || $node_id == 'Cancel') {
        $logDoc = new Request_Log($db);
        $logDoc->form = new Form($db, $formID);
        $logDoc->request_id = $insert_result;

        if ($node_id == 'Save') {
            $logDoc->details = 'Saved';
        } else {
            $logDoc->details = 'Cancelled';
        }

        $logDoc->created_by = new Person($db, $auth['id']);
        $logDoc->date_created = $date;
        $logDoc->save();
    }

    $myRequest->data = $fields;
    $myRequest->modify();
}

if ($node_id != 'Save' && $node_id != 'Cancel') {
    $myRequest->processWF();
}

$json = array("status" => "SUCCESS", "message" => 'Successfully executed action on server.');
echo json_encode($json);
//print_r($myRequest->data);